package com.example.demo.controller;


import com.example.demo.service.WechatService;
import jakarta.servlet.http.HttpSession;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
public class UserController {
  private static final Logger logger = LoggerFactory.getLogger(UserController.class);

  private final WechatService wechatService;

  public UserController(WechatService wechatService) {
    this.wechatService = wechatService;
  }

  /**
   * 获取登录的二维码
   * @param httpSession session
   * @return 二维码对应的系统ID(用于触发扫码后的回调)
   */
  @GetMapping("/getQrCode")
  public String getLoginQrCode(HttpSession httpSession) {
    return this.wechatService.getLoginQrCode(httpSession);
  }

  /**
   *  根据二维码标识获取用户openId=>获取用户信息
   * @param ticket
   * @return
   */
  @RequestMapping("wechatToken")
  public WechatToken getWechatToken(String ticket){
    WechatToken wechatToken = new WechatToken();
    if(WechatController.map.get(ticket) == null){
      return wechatToken;
    }
    String openId = WechatController.map.get(ticket);
    wechatToken.setOpenId(openId);
    WechatController.map.remove(ticket);

    wechatToken.setToken(getTokenByOpenId(openId));
    return wechatToken;
  }

  private String getTokenByOpenId(String openId) {
    if (new Date().getTime() %2 == 0) {
      return "342rfasdfsdgty46";
    } else {
      return null;
    }
  }

  @Getter
  @Setter
  public static class WechatToken {
    private String openId;
    private String token;
  }
}
